package com.xf.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableTest {
    public static void main(String[] args) throws Exception {
        // 1:实现Callable接口创建多线程
        MyCallable myCallable = new MyCallable();
        // 获取线程执行完毕之后的结果,并且也是作为线程创建的参数
        FutureTask<String> ft = new FutureTask<>(myCallable);
        // 创建线程
        Thread thread = new Thread(ft);
        // 启动线程
        thread.start();
        // 获取返回值
        String s = ft.get();
        System.out.println(s);

        // 2:通过匿名内部类创建
        FutureTask<String> ft2 = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() {
                int sum = 0;
                for (int i = 0; i < 100; i++) {
                    sum += i;
                }
                return sum + "";
            }
        });
        Thread thread2 = new Thread(ft2);
        thread2.start();
        System.out.println(ft2.get());
    }
}

class MyCallable implements Callable<String> {
    @Override
    public String call() {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum + "";
    }
}